import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import styled from 'styled-components';
import { ArrowBack, User, Mail, Calendar, Shield, Timeline, AccessTime, Award } from '@mui/icons-material';
import { Button, Divider, Chip, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper } from '@mui/material';
import logger from '../../utils/logger';

const Container = styled.div`
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
`;

const Header = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e7eb;
`;

const TitleSection = styled.div`
  display: flex;
  align-items: center;
  gap: 16px;
`;

const BackButton = styled(Button)`
  min-width: auto;
  padding: 8px;
`;

const UserInfoCard = styled.div`
  background-color: #ffffff;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
`;

const UserHeader = styled.div`
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
`;

const Avatar = styled.div`
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: #3b82f6;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 32px;
  font-weight: bold;
`;

const UserInfo = styled.div`
  flex: 1;
`;

const UserName = styled.h2`
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
`;

const UserEmail = styled.p`
  margin: 0 0 12px 0;
  color: #6b7280;
  font-size: 16px;
`;

const UserMeta = styled.div`
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
`;

const MetaItem = styled.div`
  display: flex;
  align-items: center;
  gap: 6px;
  color: #6b7280;
`;

const DetailsGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
`;

const DetailCard = styled.div`
  background-color: #ffffff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
`;

const DetailTitle = styled.h3`
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
`;

const DetailItem = styled.div`
  display: flex;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #f3f4f6;
  
  &:last-child {
    border-bottom: none;
  }
`;

const DetailLabel = styled.span`
  color: #6b7280;
  font-weight: 500;
`;

const DetailValue = styled.span`
  color: #1f2937;
  font-weight: 500;
`;

const ActivityCard = styled.div`
  background-color: #ffffff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-top: 24px;
`;

const ActionSection = styled.div`
  display: flex;
  gap: 12px;
`;

const UserDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [activities, setActivities] = useState([]);
  const [analysisHistory, setAnalysisHistory] = useState([]);

  // 获取用户详情数据
  useEffect(() => {
    logger.info(`正在加载用户ID: ${id} 的详细信息`);
    const fetchUserDetails = async () => {
      try {
        // 模拟加载用户数据
        const mockUser = {
          id,
          username: `user${id}`,
          email: `user${id}@example.com`,
          fullName: id % 2 === 0 ? '张三' : '李四',
          phone: `138****${String(id).padEnd(4, '0')}`,
          createdAt: new Date(Date.now() - Math.floor(Math.random() * 100) * 24 * 60 * 60 * 1000).toISOString(),
          lastLogin: new Date(Date.now() - Math.floor(Math.random() * 7) * 24 * 60 * 60 * 1000).toISOString(),
          isActive: Math.random() > 0.2,
          isVip: Math.random() > 0.7,
          vipExpireDate: Math.random() > 0.7 ? new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString() : null,
          analysesCount: Math.floor(Math.random() * 100),
          totalSpent: Math.floor(Math.random() * 10000) / 100,
          lastAnalysisDate: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString(),
          favoriteAnalysisTypes: ['bazi', 'face', 'tarot'].slice(0, Math.floor(Math.random() * 3) + 1),
          loginCount: Math.floor(Math.random() * 100),
          avatar: `https://ui-avatars.com/api/?name=${id}&background=random`
        };

        // 模拟活动记录
        const mockActivities = Array.from({ length: 5 }, (_, i) => ({
          id: i + 1,
          type: ['login', 'analysis', 'payment', 'profile_update'][Math.floor(Math.random() * 4)],
          description: [
            '用户登录系统',
            '进行了八字分析',
            '购买了VIP会员',
            '更新了个人资料'
          ][Math.floor(Math.random() * 4)],
          timestamp: new Date(Date.now() - i * 24 * 60 * 60 * 1000).toISOString(),
          ipAddress: `192.168.1.${Math.floor(Math.random() * 255)}`
        }));

        // 模拟分析历史
        const mockAnalysisHistory = Array.from({ length: 8 }, (_, i) => ({
          id: i + 1,
          type: ['bazi', 'face', 'palm', 'tarot', 'dream'][Math.floor(Math.random() * 5)],
          title: [
            '八字排盘分析',
            '面相分析',
            '手相解读',
            '塔罗牌占卜',
            '梦境解析'
          ][Math.floor(Math.random() * 5)],
          date: new Date(Date.now() - i * 2 * 24 * 60 * 60 * 1000).toISOString(),
          duration: Math.floor(Math.random() * 60) + 30,
          paymentAmount: Math.random() > 0.5 ? Math.floor(Math.random() * 100) : 0
        }));

        setTimeout(() => {
          setUser(mockUser);
          setActivities(mockActivities);
          setAnalysisHistory(mockAnalysisHistory);
          setLoading(false);
          logger.info(`用户ID: ${id} 的详细信息加载完成`);
        }, 600);
      } catch (error) {
        console.error('获取用户详情失败:', error);
        logger.error(`获取用户ID: ${id} 详情失败: ${error.message}`);
        setLoading(false);
      }
    };

    fetchUserDetails();
  }, [id]);

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 处理返回
  const handleBack = () => {
    navigate('/admin/users');
  };

  // 切换用户状态
  const handleToggleStatus = () => {
    logger.info(`切换用户ID: ${id} 的状态`);
    setUser(prev => ({ ...prev, isActive: !prev.isActive }));
  };

  // 重置密码
  const handleResetPassword = () => {
    logger.info(`重置用户ID: ${id} 的密码`);
    alert('密码重置链接已发送至用户邮箱');
  };

  // 分析类型映射
  const analysisTypeMap = {
    'bazi': '八字分析',
    'face': '面相分析',
    'palm': '手相分析',
    'tarot': '塔罗牌占卜',
    'dream': '梦境解析'
  };

  if (loading) {
    return <Container>加载中...</Container>;
  }

  if (!user) {
    return (
      <Container>
        <Header>
          <BackButton onClick={handleBack} variant="outlined" startIcon={<ArrowBack />}>
            返回列表
          </BackButton>
        </Header>
        <div>用户不存在或已被删除</div>
      </Container>
    );
  }

  return (
    <Container>
      <Header>
        <TitleSection>
          <BackButton onClick={handleBack} variant="outlined" startIcon={<ArrowBack />}>
            返回列表
          </BackButton>
          <h1>用户详情</h1>
        </TitleSection>
        <ActionSection>
          <Button 
            variant="contained" 
            color={user.isActive ? "warning" : "success"} 
            onClick={handleToggleStatus}
          >
            {user.isActive ? '禁用用户' : '启用用户'}
          </Button>
          <Button variant="outlined" onClick={handleResetPassword}>
            重置密码
          </Button>
        </ActionSection>
      </Header>

      <UserInfoCard>
        <UserHeader>
          <Avatar>
            {user.username.charAt(0).toUpperCase()}
          </Avatar>
          <UserInfo>
            <UserName>{user.username}</UserName>
            <UserEmail>{user.email}</UserEmail>
            <UserMeta>
              <MetaItem>
                <Shield size={16} />
                <span>{user.isVip ? 'VIP用户' : '普通用户'}</span>
                {user.isVip && (
                  <Chip 
                    label={`有效期至: ${formatDate(user.vipExpireDate)}`} 
                    size="small" 
                    color="primary" 
                    variant="outlined" 
                  />
                )}
              </MetaItem>
              <MetaItem>
          <Timeline size={16} />
          <span>分析次数: {user.analysesCount}</span>
        </MetaItem>
              <MetaItem>
          <AccessTime size={16} />
          <span>最后登录: {formatDate(user.lastLogin)}</span>
        </MetaItem>
            </UserMeta>
          </UserInfo>
        </UserHeader>
      </UserInfoCard>

      <DetailsGrid>
        <DetailCard>
          <DetailTitle>基本信息</DetailTitle>
          <DetailItem>
            <DetailLabel>用户名</DetailLabel>
            <DetailValue>{user.username}</DetailValue>
          </DetailItem>
          <DetailItem>
            <DetailLabel>真实姓名</DetailLabel>
            <DetailValue>{user.fullName || '-'}</DetailValue>
          </DetailItem>
          <DetailItem>
            <DetailLabel>邮箱</DetailLabel>
            <DetailValue>{user.email}</DetailValue>
          </DetailItem>
          <DetailItem>
            <DetailLabel>手机号码</DetailLabel>
            <DetailValue>{user.phone}</DetailValue>
          </DetailItem>
          <DetailItem>
            <DetailLabel>注册时间</DetailLabel>
            <DetailValue>{formatDate(user.createdAt)}</DetailValue>
          </DetailItem>
          <DetailItem>
            <DetailLabel>用户状态</DetailLabel>
            <DetailValue>
              <span style={{ 
                color: user.isActive ? '#10b981' : '#6b7280',
                fontWeight: 600
              }}>
                {user.isActive ? '活跃' : '已禁用'}
              </span>
            </DetailValue>
          </DetailItem>
        </DetailCard>

        <DetailCard>
          <DetailTitle>使用统计</DetailTitle>
          <DetailItem>
            <DetailLabel>总分析次数</DetailLabel>
            <DetailValue>{user.analysesCount}</DetailValue>
          </DetailItem>
          <DetailItem>
            <DetailLabel>累计消费</DetailLabel>
            <DetailValue style={{ color: '#f59e0b', fontWeight: 600 }}>¥{user.totalSpent.toFixed(2)}</DetailValue>
          </DetailItem>
          <DetailItem>
            <DetailLabel>登录次数</DetailLabel>
            <DetailValue>{user.loginCount}</DetailValue>
          </DetailItem>
          <DetailItem>
            <DetailLabel>最后分析时间</DetailLabel>
            <DetailValue>{formatDate(user.lastAnalysisDate)}</DetailValue>
          </DetailItem>
          <DetailItem>
            <DetailLabel>偏好分析类型</DetailLabel>
            <DetailValue>
              {user.favoriteAnalysisTypes.length > 0 ? (
                user.favoriteAnalysisTypes.map(type => (
                  <Chip 
                    key={type} 
                    label={analysisTypeMap[type] || type} 
                    size="small" 
                    style={{ marginRight: '6px', marginBottom: '6px' }}
                  />
                ))
              ) : (
                '-'  
              )}
            </DetailValue>
          </DetailItem>
        </DetailCard>
      </DetailsGrid>

      <ActivityCard>
        <DetailTitle>最近分析记录</DetailTitle>
        <TableContainer component={Paper} style={{ marginTop: '16px' }}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>类型</TableCell>
                <TableCell>标题</TableCell>
                <TableCell>分析时间</TableCell>
                <TableCell>耗时(秒)</TableCell>
                <TableCell>支付金额</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {analysisHistory.map((item) => (
                <TableRow key={item.id}>
                  <TableCell>
                    <Chip 
                      label={analysisTypeMap[item.type] || item.type} 
                      size="small" 
                    />
                  </TableCell>
                  <TableCell>{item.title}</TableCell>
                  <TableCell>{formatDate(item.date)}</TableCell>
                  <TableCell>{item.duration}</TableCell>
                  <TableCell>
                    {item.paymentAmount > 0 ? 
                      <span style={{ color: '#f59e0b', fontWeight: 600 }}>¥{item.paymentAmount.toFixed(2)}</span> : 
                      '免费'
                    }
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      </ActivityCard>

      <ActivityCard>
        <DetailTitle>最近活动记录</DetailTitle>
        <TableContainer component={Paper} style={{ marginTop: '16px' }}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>活动类型</TableCell>
                <TableCell>描述</TableCell>
                <TableCell>时间</TableCell>
                <TableCell>IP地址</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {activities.map((activity) => (
                <TableRow key={activity.id}>
                  <TableCell>
                    <Chip 
                      label={activity.type} 
                      size="small" 
                    />
                  </TableCell>
                  <TableCell>{activity.description}</TableCell>
                  <TableCell>{formatDate(activity.timestamp)}</TableCell>
                  <TableCell>{activity.ipAddress}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      </ActivityCard>
    </Container>
  );
};

export default UserDetail;